package JaggSoft;

import JaggSoft.Utilidades.*;
import java.awt.Component;
import java.awt.event.*;
import java.util.TimerTask;
import javax.swing.*;
import javax.swing.border.*;

public class Principal extends javax.swing.JFrame {
    private String id_bitacora="-1";
    private AbstractBorder borde_default;
    private JButton jbAlarma=null;
    private java.util.Timer temporizador=null;
    public Principal() {
        initComponents();
        borde_default=(AbstractBorder)desktopPane.getBorder();
        IniciarLogin();
    }
    public final void IniciarLogin(){
        for(Component c:jpMenu.getComponents())
            if(c instanceof JButton || c instanceof JSeparator)
                jpMenu.remove(c);
        jlMensaje.setText("");
        id_bitacora="-1";
        this.setVisible(false);
        this.setLocationRelativeTo(null);
        jdLogin.setSize(280,165);
        jdLogin.setLocationRelativeTo(this);
        jdLogin.show();
    }
    public final void CerrarSesionBitacora(){
        if(!id_bitacora.equals("-1")){
            if(Conexion.bitacora) Util.AccionBitacora(id_bitacora,"Cerrar Sesión");
            if(Conexion.bitacora) Util.ClausurarBitacora(id_bitacora);
        }
        temporizador.cancel();
        for(JInternalFrame j:desktopPane.getAllFrames()){
            try { j.setClosed(true); } catch (Exception ex) {System.err.println(ex.getMessage());}}
    }
    private void SetDatosBoton(JButton boton,String nombre_boton,int x,int y,int ancho,int alto){
        boton.setToolTipText(nombre_boton);
        boton.setBounds(x,y,ancho,alto);
        jpMenu.add(boton);
    }
    private void EstablecerPermisos(){
        JButton jbCerrarSesion=new JButton(new ImageIcon(getClass().getResource("/Recursos/cerrar_sesion.png")));
        JButton jbConfiguracion=new JButton(new ImageIcon(getClass().getResource("/Recursos/cofiguracion.png")));
        JSeparator separador=new JSeparator(SwingConstants.HORIZONTAL);
        separador.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
        if(Conexion.tipo==Util.Tipo.ADMINISTRADOR){
            JButton jbAdministracionReportes=new JButton();
            
            JButton jbBodega=new JButton(new ImageIcon(getClass().getResource("/Recursos/bodega.png")));
            JButton jbUsuarios=new JButton(new ImageIcon(getClass().getResource("/Recursos/usuarios.png")));
            JButton jbMarcas=new JButton(new ImageIcon(getClass().getResource("/Recursos/marca.png")));
            JButton jbProveedores=new JButton(new ImageIcon(getClass().getResource("/Recursos/proveedores.png")));
            JButton jbProducto=new JButton(new ImageIcon(getClass().getResource("/Recursos/producto.png")));
            JButton jbArea=new JButton(new ImageIcon(getClass().getResource("/Recursos/area.png")));
            
            JButton jbReporteInventario=new JButton(new ImageIcon(getClass().getResource("/Recursos/reporte_inventario.png")));
            JButton jbReporteEntrada=new JButton(new ImageIcon(getClass().getResource("/Recursos/reporte_entradas.png")));
            JButton jbReporteSolicitud=new JButton(new ImageIcon(getClass().getResource("/Recursos/reporte_solicitudes.png")));
            JButton jbReporteDevoluciones=new JButton(new ImageIcon(getClass().getResource("/Recursos/reporte_devoluciones.png")));
            JButton jbReporteMasMenosSolicitado=new JButton(new ImageIcon(getClass().getResource("/Recursos/reporte_masmenos_solicitado.png")));
            JButton jbReporteBitacora=new JButton(new ImageIcon(getClass().getResource("/Recursos/reporte_bitacora.png")));
            
            SetDatosBoton(jbAdministracionReportes,"Reportes/Administración",6,6,48,48);
            SetDatosBoton(jbCerrarSesion,"Cerrar Sesión",6,60,48,48);
            SetDatosBoton(jbConfiguracion,"Configuración",6,114,48,48);
            separador.setBounds(0,163,70,4);
            
            
            SetDatosBoton(jbBodega,"Bodegas",6,168,48,48);
            SetDatosBoton(jbUsuarios,"Usuarios",6,222,48,48);
            SetDatosBoton(jbMarcas,"Marcas",6,276,48,48);
            SetDatosBoton(jbProveedores,"Proveedores",6,330,48,48);
            SetDatosBoton(jbProducto,"Productos",6,384,48,48);
            SetDatosBoton(jbArea,"Area",6,438,48,48);
            
            SetDatosBoton(jbReporteInventario,"Reporte de Inventario",6,168,48,48);
            SetDatosBoton(jbReporteEntrada,"Reporte de Entradas",6,222,48,48);
            SetDatosBoton(jbReporteSolicitud,"Reporte de Solicitudes",6,276,48,48);
            SetDatosBoton(jbReporteDevoluciones,"Reporte de Devoluciones",6,330,48,48);
            SetDatosBoton(jbReporteMasMenosSolicitado,"Reporte de Producto Mas/Menos Solicitado",6,384,48,48);
            SetDatosBoton(jbReporteBitacora,"Reporte de Bitácora",6,438,48,48);
            
            jbAdministracionReportes.addActionListener(new ManejadorAdministracionReportes(jbAdministracionReportes,new JButton[]{jbBodega,jbUsuarios,jbMarcas,jbProveedores,jbProducto,jbArea},new JButton[]{jbReporteInventario,jbReporteEntrada,jbReporteSolicitud}));
            
            jbBodega.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.Bodegas"));
            jbUsuarios.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.Usuarios"));
            jbMarcas.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.Marcas"));
            jbProveedores.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.Proveedores"));
            jbProducto.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.Productos"));
            jbArea.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.Area"));
            
            jbReporteInventario.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.ReporteInventario"));
            jbReporteEntrada.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.ReporteEntrada"));
            jbReporteSolicitud.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.ReporteSolicitudes"));
            jbReporteDevoluciones.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.ReporteDevoluciones"));
            jbReporteMasMenosSolicitado.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.ReporteProductoMasMenosSolicitado"));
            jbReporteBitacora.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.ReporteBitacora"));
        }
        else{
            JButton jbSolicitud=new JButton(new ImageIcon(getClass().getResource("/Recursos/solicitud.png")));
            JButton jbDevolucion=new JButton(new ImageIcon(getClass().getResource("/Recursos/devolucion.png")));
            JButton jbIngreso=new JButton(new ImageIcon(getClass().getResource("/Recursos/ingresos.png")));
            JButton jbSolicitantes=new JButton(new ImageIcon(getClass().getResource("/Recursos/solicitantes.png")));
            
            SetDatosBoton(jbCerrarSesion,"Cerrar Sesión",6,6,48,48);
            SetDatosBoton(jbConfiguracion,"Configuración",6,60,48,48);
            separador.setBounds(0,110,70,4);
            
            SetDatosBoton(jbSolicitud,"Solicitudes",6,114,48,48);
            SetDatosBoton(jbDevolucion,"Devoluciones",6,168,48,48);
            SetDatosBoton(jbIngreso,"Ingreso y Distribución de Productos",6,222,48,48);
            SetDatosBoton(jbSolicitantes,"Solicitantes",6,276,48,48);
            
            jbSolicitud.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.Solicitud"));
            jbDevolucion.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.Devoluciones"));
            jbIngreso.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.Ingreso"));
            jbSolicitantes.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.Solicitante"));
        }
        jpMenu.add(separador);
        jbCerrarSesion.addActionListener(new ManejadorEventoCerrarSesion(this));
        jbConfiguracion.addActionListener(new ManejadorEventoClickConfiguracion(this.desktopPane));
        
    }
    private void GestionarAlarma(int meses){
        JTable tabla= Conexion.ObtenerTabla("SELECT COUNT(*) FROM inventario_bodega WHERE TIMESTAMPDIFF(MONTH,fecha_vencimiento,CURRENT_DATE()) >= -"+meses,new String[]{"vencidos"});
        if(tabla.getRowCount()>0){
            jbAlarma=new JButton(new ImageIcon(getClass().getResource("/Recursos/alarma1.png")));
            SetDatosBoton(jbAlarma,"Vencimiento de Productos",6,desktopPane.getHeight()-60,48,48);
            jbAlarma.addActionListener(new ManejadorEventoClickProductosVencidos(this.desktopPane,meses));
            temporizador=new java.util.Timer();
            TimerTask tarea=new TimerTask() {
                String num="2";
                boolean funcionando=true;
                @Override
                public void run() {
                    jbAlarma.setIcon(new ImageIcon(getClass().getResource("/Recursos/alarma"+num+".png")));
                    num=(num.equals("2")?"3":"2");
                }
            };
            temporizador.schedule(tarea,1000,500);
        }
    }
    private void FondoSistema(){
        ConfiguracionUsuario conf=Conexion.ObtenerConfiguracion();
        if(conf!=null){
            ImagenFondo img=new ImagenFondo(conf.getFondoPantalla());
            img.setDimensionesPanel(desktopPane.getWidth(),desktopPane.getHeight());
            if(!conf.getFondoPantalla().equals(""))
                desktopPane.setBorder(img);
            else
                desktopPane.setBorder(borde_default);
            GestionarAlarma(conf.getMeses());
        }
        else{
            desktopPane.setBorder(borde_default);
            GestionarAlarma(6);
        }
    }
    private class ManejadorEventoClickConfiguracion extends ManejadorEventoClick{
        public ManejadorEventoClickConfiguracion(JDesktopPane panel) {
            super(panel,"");
        }
        @Override
        public void actionPerformed(ActionEvent e) {
            for(JInternalFrame j:super.getPanel().getAllFrames()){
                if(j.getClass().getName().equals("JaggSoft.Configuracion")){
                    try { j.setSelected(true); } catch (Exception ex) {System.err.println(ex.getMessage());}
                    if(JOptionPane.showConfirmDialog(null,"Desea cerrar la ventana de "+j.getTitle()+"?","Cerrar Ventana",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
                        j.dispose();
                        try {
                            JInternalFrame nuevo=new Configuracion(super.getPanel(),borde_default);
                            super.getPanel().add(nuevo);
                            nuevo.show();
                            return;
                        } catch (Exception ex) {JOptionPane.showMessageDialog(null,"Error al crear una nueva ventana","JaggSoft",JOptionPane.INFORMATION_MESSAGE); }
                    }
                    else return;
                }
            }
            try {
                JInternalFrame nuevo=new Configuracion(super.getPanel(),borde_default);
                super.getPanel().add(nuevo);
                nuevo.show();
            } catch (Exception ex) { JOptionPane.showMessageDialog(null,"Error al crear una nueva ventana","JaggSoft",JOptionPane.INFORMATION_MESSAGE); }
        }
    }
    private class ManejadorEventoClickProductosVencidos extends ManejadorEventoClick{
        private int meses;
        public ManejadorEventoClickProductosVencidos(JDesktopPane panel,int meses) {
            super(panel,"");
            this.meses=meses;
        }
        @Override
        public void actionPerformed(ActionEvent e) {
            for(JInternalFrame j:super.getPanel().getAllFrames()){
                if(j.getClass().getName().equals("JaggSoft.ProductosVencidos")){
                    try { j.setSelected(true); } catch (Exception ex) {System.err.println(ex.getMessage());}
                    if(JOptionPane.showConfirmDialog(null,"Desea cerrar la ventana de "+j.getTitle()+"?","Cerrar Ventana",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
                        j.dispose();
                        try {
                            JInternalFrame nuevo=new ProductosVencidos(this.meses);
                            super.getPanel().add(nuevo);
                            nuevo.show();
                            return;
                        } catch (Exception ex) {JOptionPane.showMessageDialog(null,"Error al crear una nueva ventana","JaggSoft",JOptionPane.INFORMATION_MESSAGE); }
                    }
                    else return;
                }
            }
            try {
                JInternalFrame nuevo=new ProductosVencidos(this.meses);
                super.getPanel().add(nuevo);
                nuevo.show();
            } catch (Exception ex) { JOptionPane.showMessageDialog(null,"Error al crear una nueva ventana","JaggSoft",JOptionPane.INFORMATION_MESSAGE); }
        }
    }
    private Util.Tipo ValidarPermisos(){
        JTable tabla=Conexion.ObtenerTabla("SELECT id_usuario,id_tipo,guardar_bitacora FROM usuario WHERE usuario='"+Util.ComponerTexto(jtfUsuario.getText())+"' AND pass='"+Util.ComponerTexto(jtfPassword.getText())+"'",new String[]{"Tipo","Descripcion","Bitacora"});
        if(tabla.getRowCount()>0){
            Conexion.ID=tabla.getValueAt(0,0).toString();
            Conexion.bitacora=(tabla.getValueAt(0,2).toString().equals("s")?true:false);
            if(tabla.getValueAt(0,1).toString().equals("1"))
                return Util.Tipo.ADMINISTRADOR;
            return Util.Tipo.USUARIO;
        }
        return Util.Tipo.NINGUNO;
    }
    private boolean ValidarCampos(){
        if(jtfUsuario.getText().length()==0)
            jlMensaje.setText("Debe ingresar el usuario"+(jtfPassword.getText().length()>0?".":" y contraseña."));
        else{
            if(jtfPassword.getText().length()==0)
                jlMensaje.setText("Debe ingresar la constraseña.");
            else
                return true;
        }
        return false;
    }
    private void SoloAlfanumericos(KeyEvent evt){
        char tecla=evt.getKeyChar();
        if(tecla==10){
            Login();
            return;
        }
        if((tecla<'a'||tecla>'z')&&(tecla<'A'||tecla>'Z')&&(tecla<'0'||tecla>'9')&&(tecla!=8)&&(tecla!=35)&&(tecla!=36)&&(tecla!=127)&&(evt.getKeyChar()!='ñ')&&(evt.getKeyChar()!='Ñ')){
            evt.consume();
            jlMensaje.setText("Solo se permiten caracter alfanuméricos.");
        }
        else
            jlMensaje.setText("");
    }
    private void Login(){
        if(ValidarCampos()){
            Conexion.tipo=ValidarPermisos();
            if(Conexion.tipo==Util.Tipo.NINGUNO)
                jlMensaje.setText("El usuario no existe.");
            else{
                EstablecerPermisos();
                FondoSistema();
                if(Conexion.bitacora) id_bitacora=Util.IniciarBitacora("Principal");
                if(Conexion.bitacora) Util.AccionBitacora(id_bitacora,"Login");
                this.setVisible(true);
                jdLogin.setVisible(false);
                jtfUsuario.setText("");
                jtfPassword.setText("");
                jtfUsuario.grabFocus();
            }
        }
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jdLogin = new javax.swing.JDialog();
        jtfUsuario = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        btnLogin = new javax.swing.JButton();
        jtfPassword = new javax.swing.JPasswordField();
        jlMensaje = new javax.swing.JLabel();
        desktopPane = new javax.swing.JDesktopPane();
        jpMenu = new javax.swing.JPanel();

        jdLogin.setTitle("Inicio de Sesión");
        jdLogin.setIconImage(new ImageIcon(getClass().getResource("/Recursos/icono.png")).getImage());
        jdLogin.addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                jdLoginWindowClosing(evt);
            }
        });

        jtfUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtfUsuarioKeyTyped(evt);
            }
        });

        jLabel2.setText("Usuario:");

        jLabel3.setText("Contraeña:");

        btnLogin.setText("Ingresar");
        btnLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLoginActionPerformed(evt);
            }
        });

        jtfPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtfPasswordKeyTyped(evt);
            }
        });

        jlMensaje.setForeground(new java.awt.Color(255, 0, 0));
        jlMensaje.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jlMensaje.setText("mensaje");

        javax.swing.GroupLayout jdLoginLayout = new javax.swing.GroupLayout(jdLogin.getContentPane());
        jdLogin.getContentPane().setLayout(jdLoginLayout);
        jdLoginLayout.setHorizontalGroup(
            jdLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jdLoginLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jdLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jlMensaje, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jdLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jdLoginLayout.createSequentialGroup()
                            .addComponent(jLabel2)
                            .addGap(18, 18, 18)
                            .addComponent(jtfUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jdLoginLayout.createSequentialGroup()
                            .addComponent(jLabel3)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(jdLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jtfPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(jdLoginLayout.createSequentialGroup()
                                    .addGap(10, 10, 10)
                                    .addComponent(btnLogin))))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jdLoginLayout.setVerticalGroup(
            jdLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jdLoginLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jdLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtfUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jdLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jtfPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnLogin)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jlMensaje)
                .addContainerGap())
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("StockManager");
        setIconImage(new ImageIcon(getClass().getResource("/Recursos/icono.png")).getImage());
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        javax.swing.GroupLayout jpMenuLayout = new javax.swing.GroupLayout(jpMenu);
        jpMenu.setLayout(jpMenuLayout);
        jpMenuLayout.setHorizontalGroup(
            jpMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 70, Short.MAX_VALUE)
        );
        jpMenuLayout.setVerticalGroup(
            jpMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 600, Short.MAX_VALUE)
        );

        jpMenu.setBounds(0, 0, 70, 600);
        desktopPane.add(jpMenu, javax.swing.JLayeredPane.DEFAULT_LAYER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(desktopPane, javax.swing.GroupLayout.DEFAULT_SIZE, 1000, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(desktopPane, javax.swing.GroupLayout.DEFAULT_SIZE, 650, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoginActionPerformed
        Login();
    }//GEN-LAST:event_btnLoginActionPerformed
    private void jdLoginWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_jdLoginWindowClosing
        System.exit(0);
    }//GEN-LAST:event_jdLoginWindowClosing
    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        jpMenu.setBounds(jpMenu.getX(),jpMenu.getY(),jpMenu.getWidth(),this.getHeight());
        if(desktopPane.getBorder() instanceof ImagenFondo)
            ((ImagenFondo)desktopPane.getBorder()).setDimensionesPanel(desktopPane.getWidth(),desktopPane.getHeight());
        if(jbAlarma!=null)
            jbAlarma.setLocation(6,desktopPane.getHeight()-60);
    }//GEN-LAST:event_formComponentResized
    private void jtfPasswordKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfPasswordKeyTyped
        SoloAlfanumericos(evt);
    }//GEN-LAST:event_jtfPasswordKeyTyped
    private void jtfUsuarioKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfUsuarioKeyTyped
        SoloAlfanumericos(evt);
    }//GEN-LAST:event_jtfUsuarioKeyTyped
    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        for(JInternalFrame j:desktopPane.getAllFrames()){
            try { j.setClosed(true); } catch (Exception ex) {System.err.println(ex.getMessage());}}
        if(!id_bitacora.equals("-1")){
            if(Conexion.bitacora) Util.AccionBitacora(id_bitacora,"Cerrar Sesión");
            if(Conexion.bitacora) Util.ClausurarBitacora(id_bitacora);
        }
    }//GEN-LAST:event_formWindowClosing
    public static void main(String args[]) {
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
           for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Principal();
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnLogin;
    private javax.swing.JDesktopPane desktopPane;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JDialog jdLogin;
    private javax.swing.JLabel jlMensaje;
    private javax.swing.JPanel jpMenu;
    private javax.swing.JPasswordField jtfPassword;
    private javax.swing.JTextField jtfUsuario;
    // End of variables declaration//GEN-END:variables
}